/*--------------------------------------------------------------------------
    This source file is part of Abraxas Game Engine
    For the latest info, see http://code.google.com/abraxasge/
    Copyright (C) 2009, Andrew LeRoy <aleroy@member.igda.org>
    ---

    This program is free software; you can redistribute it and/or
    modify it under the terms of the GNU General Public License
    as published by the Free Software Foundation; either version 2
    of the License, or (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program; if not, write to the Free Software
    Foundation, Inc., 51 Franklin Street, Fifth Floor,
    Boston, MA  02110-1301, USA.
--------------------------------------------------------------------------*/
//#include "AbxStableHeaders.h"
#include "AbxLog.hpp"
#include "AbxException.hpp"


namespace Abx
{
    Log::Log(String const& name, LogDest writeTo, LogLevel level, LogEntryType entryTypes)
        : mName(name), mDest(writeTo), mLevel(level), mEntry(entryTypes)
    {
        if (mDest & LOG_DEST_FILE)
        {
            mfpLog.open(name.c_str());
            if (mfpLog.fail())
            {
                ABX_EXCEPT( Exception::ERR_FILE_NOT_FOUND, "Failed to open file '" + name + "'", "Log::Log()" );
            }
        }
    }
    
    Log::~Log()
    {
        if (mDest & LOG_DEST_FILE)
        {
            mfpLog.close();
        }
    }
    
    void Log::logMessage(String const& message, LogEntryType entryType)
    {
        if (mEntry & entryType)
        {
            if (mDest & LOG_DEST_CONSOLE)
            {
                std::cerr << message << std::endl;
            }

            // Write time into log
            if (mDest & LOG_DEST_FILE)
            {
                struct tm *pTime;
                time_t ctTime; time(&ctTime);
                pTime = localtime( &ctTime );
                mfpLog << std::setw(2) << std::setfill('0') << pTime->tm_hour
                    << ":" << std::setw(2) << std::setfill('0') << pTime->tm_min
                    << ":" << std::setw(2) << std::setfill('0') << pTime->tm_sec 
                    << ": " << message << std::endl;

                // Flush stcmdream to ensure it is written (incase of a crash, we need log to be up to date)
                mfpLog.flush();
            }
        }
    }

    Log::Stream Log::stream(LogEntryType entryType)
    {
        return Stream(this, entryType);
    }
} // namespace Abx
